#include "udp_client.hpp"
#include "Commn.hpp"
#include "Log.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace LogModule;
#include <limits>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Please use for ./client_udp + ip + port" << std::endl;
        Die(USE_ERROR);
    }
    int socketfd = ::socket(AF_INET6, SOCK_DGRAM, 0);

    // char = argv[1];
    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    if (socketfd < 0)
    {
        Die(SOCKET_ERROR);
    }
    LOG(LogLevel::DEBUG) << "socket create success, fd is " << socketfd;
    
    sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = ::inet_addr(ip.c_str()); 
    server.sin_port = ::htons(port);
    socklen_t len = sizeof(server);
    std::string message;
    
    while(true)
    {
        std::cout << "Please Enter# ";
        getline(std::cin,message);
        // std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        ::sendto(socketfd,message.c_str(),message.size(),0,CONV(&server),len);   

        sockaddr_in peer;
        socklen_t Len = sizeof(peer); //一定要初始化

        char inbuffer[1024];
        int n = ::recvfrom(socketfd,inbuffer,sizeof(inbuffer)-1,0,CONV(&peer),&Len);
        if (n > 0)
        {
            inbuffer[n] = 0;
            LOG(LogLevel::INFO) << inbuffer;
        }
    }
    return 0;
}